package com.example.cloudpracticeplatform.controller;

import com.example.cloudpracticeplatform.common.Response;
import com.example.cloudpracticeplatform.entity.Student;
import com.example.cloudpracticeplatform.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
@CrossOrigin
public class StudentController {

    @Resource
    private StudentService studentService;

    @PostMapping("/add")
    public Response<String> addStudent(@RequestBody Student student) {
        int result = studentService.register(student);
        if (result > 0) {
            return Response.success("Student added successfully");
        } else {
            return Response.error("Failed to add student");
        }
    }

    @PostMapping("/update")
    public Response<String> updateStudent(@RequestBody Student student) {
        int result = studentService.update(student);
        if (result > 0) {
            return Response.success("Student updated successfully");
        } else {
            return Response.error("Failed to update student");
        }
    }

    @PostMapping("/delete")
    public Response<String> deleteStudent(@RequestParam Integer studentId) {
        int result = studentService.delete(studentId);
        if (result > 0) {
            return Response.success("Student deleted successfully");
        } else {
            return Response.error("Failed to delete student");
        }
    }

    @GetMapping("/{studentId}")
    public Response<Student> getStudentById(@PathVariable Integer studentId) {
        Student student = studentService.findById(studentId);
        if (student != null) {
            return Response.success(student);
        } else {
            return Response.error("Student not found");
        }
    }

    @GetMapping("/list")
    public Response<List<Student>> getStudents(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int pageSize) {
        List<Student> students = studentService.getStudents(page, pageSize);
        return Response.success(students);
    }
}